﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SQLite;
using TabbedTemplate.Models;
using TabbedTemplate.Services;

namespace TabbedTemplate.Util
{
    public class GenerateInitialDbFile {

        private IStoreService _storeService;

        public GenerateInitialDbFile(IStoreService storeService) {
            _storeService = storeService;
        }
        /// <summary>
        /// 公开变量
        /// </summary>
        //数据库名
        public const string DbName = "BeijingCacheDb.sqlite3";

        // 诗词数据库路径
        public static readonly string BeijingCacheDbPath =
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder
                    .LocalApplicationData), DbName);
        /// <summary>
        /// 私有变量
        /// </summary>

        // 数据库连接影子变量
        private SQLiteAsyncConnection _connection;

        // 数据库连接,打开后记得关闭
        private SQLiteAsyncConnection Connection =>
            _connection ??
            (_connection = new SQLiteAsyncConnection(BeijingCacheDbPath));
        public async void GenerateBeijingDbCache() {
            //await Connection.CreateTableAsync<Store>();
            List<Store> stores = new List<Store>();
            for (int i = 0; i < 500; i++) {
                var local =await _storeService.GetStoresFromWebAsync(Tag.Buffet,
                    39.915, 116.404, 10000,i);
                stores.AddRange(local);
                if (local.Count<10) break;
            }

            for (int i = 0; i < stores.Count; i++) {
                try {
                    await Connection.InsertAsync(stores[i]);
                } catch (Exception e) {

                }
                
            }
            

        }
    }
}
